﻿Imports System.IO
Public Class frmMain
    Dim proc As New Process 'make it global so dat we can kill it from outside

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'get and backfill settings
        txtInputFolder.Text = My.Settings.ReadFolder
        txtDestFolder.Text = My.Settings.DestFolder

        If My.Settings.FFmpegLoc = "notset" Then
            txtFFmpeg.Text = Application.StartupPath + "\ffmpeg.exe"
        Else
            txtFFmpeg.Text = My.Settings.FFmpegLoc
        End If

    End Sub

    Private Sub btnInput_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInput.Click
        Dim folderDlg As New FolderBrowserDialog
        folderDlg.Description = "Select folder Convert 2 AVI will look in"
        'folderDlg.ShowDialog()

        If (folderDlg.ShowDialog() = DialogResult.OK) Then

            txtInputFolder.Text = folderDlg.SelectedPath
            My.Settings.ReadFolder = txtInputFolder.Text

        End If
    End Sub

    Private Sub btnDest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDest.Click
        Dim folderDlg As New FolderBrowserDialog
        folderDlg.Description = "Select folder Convert 2 AVI will move file to"
        'folderDlg.ShowDialog()

        If (folderDlg.ShowDialog() = DialogResult.OK) Then

            txtDestFolder.Text = folderDlg.SelectedPath
            My.Settings.DestFolder = txtDestFolder.Text

        End If
    End Sub

    Private Sub btnFFmpeg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFFmpeg.Click
        Dim folderDlg As New FolderBrowserDialog
        folderDlg.Description = "Select folder where FFmpeg.exe is located"
        'folderDlg.ShowDialog()

        If (folderDlg.ShowDialog() = DialogResult.OK) Then

            txtFFmpeg.Text = folderDlg.SelectedPath + "\ffmpeg.exe"
            My.Settings.FFmpegLoc = txtFFmpeg.Text

        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            If txtFFmpeg.Text = "notset" Then
                txtFFmpeg.Text = Application.StartupPath + "\ffmpeg.exe"
                My.Settings.FFmpegLoc = txtFFmpeg.Text
            Else
                BackgroundWorker1.CancelAsync()
                If btnStart.Enabled = False Then
                    lblInfo.Text = ("Conversion Canceled!")
                    MsgBox("Conversion has been cancelled!", MsgBoxStyle.Exclamation)
                    btnStart.Enabled = True
                End If
                proc.Kill()
                File.Delete(txtInputFolder.Text & "\" & txtFile.Text)
                txtInputFolder.Text = ""
                txtStatus.Text = ""
            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        startConverstion()
    End Sub

    Function startConverstion()
        'destination path
        Dim BasePath As String = txtInputFolder.Text

        Application.DoEvents()
        cycledir(BasePath)
        Return 0
    End Function

    Private Sub cycledir(ByVal dir As String) 'bring in directory to parse

        Dim i As Integer
        Dim Directories() As String = Directory.GetDirectories(dir) 'put all directories into an array

        'loop through each one check for additional directories with in
        If Directories.Count <> 0 Then
            For i = 0 To UBound(Directories)
                Application.DoEvents()
                cycledir(Directories(i)) 'if a directory exists inside the directory passed in, parse that one.
            Next
        End If

        cyclefile(dir) 'cycle through the files.
        Application.DoEvents()

    End Sub

    Private Sub cyclefile(ByVal dir As String) 'dir is conversition and save path

        Control.CheckForIllegalCrossThreadCalls = False

        Dim fi As FileInfo
        Dim filename As String
        Dim exepath As String = txtFFmpeg.Text 'Application.StartupPath + "ffmpeg.exe"

        Dim startinfo As New System.Diagnostics.ProcessStartInfo
        Dim sr As StreamReader

        'get all files in the passed dir
        Dim Files() As String = Directory.GetFiles(dir)
        'start cycling through the files.
        For i = 0 To Files.Count - 1
            Application.DoEvents()

            fi = New FileInfo(Files(i)) 'get file info of the file to convert
            If fi.Name.EndsWith(".mp4") OrElse fi.Name.EndsWith(".mkv") Then
                Me.lblInfo.Text = Files.Count - (i + 1) & " Files Left"
                filename = fi.Name.Remove(fi.Name.Length - 4, 4) 'get rid of extension
                filename = filename & ".avi" 'ending result filename to convert to 

                ' NOT SURE ON THIS RESOLUTION
                'Dim cmd As String = " -threads 2  -y -i """ + dir + "\" + fi.Name + """ -f avi -r 29.97 -vcodec libxvid -vtag XVID -s 704x384 -aspect 16:9 -maxrate 1800k -b 1500k -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -acodec libmp3lame -ar 48000 -ab 128k -ac 2 """ + dir + "\" + filename + """" 'ffmpeg commands -y replace"
                Dim cmd As String = " -threads 2  -y -i """ + dir + "\" + fi.Name + """ -f avi -r 29.97 -vcodec libxvid -vtag XVID -s 640x360 -aspect 16:9 -maxrate 1800k -b 1500k -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -acodec libmp3lame -ar 48000 -ab 128k -ac 2 """ + dir + "\" + filename + """" 'ffmpeg commands -y replace"
                'Dim cmd As String = " -threads 2  -y -i """ + dir + "\" + fi.Name + """ -f avi -r 29.97 -vcodec libxvid -vtag XVID -s 640x480 -aspect 4:3 -maxrate 1800k -b 1500k -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -acodec libmp3lame -ar 48000 -ab 128k -ac 2 """ + dir + "\" + filename + """" 'ffmpeg commands -y replace"

                Dim ffmpegOutput As String
                Me.txtFile.Text = "Converting " + filename

                ' all parameters required to run the process
                startinfo.FileName = exepath
                startinfo.Arguments = cmd
                startinfo.UseShellExecute = False
                startinfo.WindowStyle = ProcessWindowStyle.Hidden
                startinfo.RedirectStandardError = True
                startinfo.RedirectStandardOutput = True
                startinfo.CreateNoWindow = True
                proc.StartInfo = startinfo
                proc.Start() ' start the process
                'Me.lblInfo.Text = "Conversion in progress... Please wait..."
                sr = proc.StandardError 'standard error is used by ffmpeg
                Me.btnStart.Enabled = False
                Do
                    If BackgroundWorker1.CancellationPending Then 'check if a cancellation request was made
                        'delete current processing file.
                        proc.Kill()
                        'File.Delete(dir & "\" & filename)
                        Threading.Thread.Sleep(1000)
                        ' File.Delete(dir & "\" & filename)
                        txtFile.Text = ""
                        txtStatus.Text = ""

                        Exit Sub
                    End If
                    ffmpegOutput = sr.ReadLine
                    Me.txtStatus.Text = ffmpegOutput
                Loop Until proc.HasExited And ffmpegOutput = Nothing Or ffmpegOutput = ""

                Me.txtStatus.Text = ""
                File.Move(dir & "\" & filename, "G:\My Crap\!~Sandbox\TV\Review\" & filename)
                File.Delete(dir + "\" + fi.Name)
            End If
        Next
        Me.lblInfo.Text = "Completed"

    End Sub




End Class
